# Seymore - Content Management on Rails
# 
# Copyright (c) 2006 - 2007 Thomas Mango
# 
# For license information, please visit:
# http://code.google.com/p/seymore/
# 
# File created by Thomas Mango [tsmango@gmail.com]

module ApplicationHelper
  def user_can?(action)
    return session[:user] && session[:user].can?(action)
  end
  
  def visible_root_pages
    if user_can?('modify')
      Page.find(:all, :conditions => "parent_id is null", :order => "position")
    else
      Page.find_by_sql(["SELECT DISTINCT(p.name), p.slug, p.position from pages p LEFT JOIN revisions r ON p.id = r.page_id WHERE p.parent_id is null AND r.published = ? ORDER BY p.position", true])
    end
  end
  
  def display_contextual_navigation_tree(selected_node)
    html = '<ul>'
    ancestors = selected_node.ancestors
    root = selected_node.root
    for child in root.children
      if child.has_published_revision? || user_can?('modify')
        html += display_subtree(child, selected_node, ancestors)
      end
    end
    if root.slug == selected_node.slug && user_can?('modify')
      html += '<li>&nbsp;&nbsp;'
      html += actions(root)
      html += '</li>'
    end
    return html += '</ul>'
  end
  
  def display_subtree(node, selected_node, ancestors)
    html = '<li>'
    if node.slug == selected_node.slug
      html += '&raquo; ' + link_to(node.name, {:action => "show", :id => node.slug}, :class => "selected")
    else
      html += '&raquo; ' + link_to(node.name, :action => "show", :id => node.slug)
    end
    if ancestors.include?(node) || node.slug == selected_node.slug
      html += '<ul>'
      for child in node.children
        if child.has_published_revision? || user_can?('modify')
          html += '<li>'
          html += display_subtree(child, selected_node, ancestors)
          html += '</li>'
        end
      end
      if node.slug == selected_node.slug && user_can?('modify')
        html += '<li>'
        html += actions(node)
        html += '</li>'
      end
      html += '</ul>'
    end
    return html + '</li>'
  end
  
  private
  def actions(node)
    html = ""
    html += "<select onchange=\"javascript:go_for_#{node.id}(this);\" style=\"font-size:8pt;\">"
	  html += "<option>Actions...</option>"
		html += "<option value=\"add_action\" >Add a page</option>"
		html += "<option value=\"reorder_action\">Reorder pages</option>" if user_can?('publish')
		html += "<script type=\"text/javascript\" charset=\"utf-8\">"
		html += "function go_for_#{node.id}(actions) {"
		html += "var action = actions.options[actions.selectedIndex].value;"
		html += "if(action == 'add_action') window.location = '/page/add/?parent=#{node.id}';"
		html += "else if(action == 'reorder_action') window.location = '/page/reorder/#{node.id}';" if user_can?('publish')
		html += "}"
		html += "</script>"
	  html += "</select>"
	  return html
  end
end
